<template>
  <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :size="formSize"
      class="demo-form"
      label-width="120px"
      status-icon
      style="margin-top: 20px"
  >
    <el-form-item disabled label="用户名" prop="account">
      <el-input v-model="form.account" disabled style="width: 100%"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" style="width: 100%" type="password"/>
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name" style="width: 100%"/>
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="form.phone" style="width: 100%"/>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="form.email" style="width: 100%"/>
    </el-form-item>
    <el-form-item label="部门" prop="department">
      <el-select v-model="form.department" disabled style="width: 100%">
        <el-option v-for="department in optionsDepartment" :key="department.value" :label="department.label"
                   :value="department.value"/>
      </el-select>
    </el-form-item>
    <el-form-item label="职位" prop="position">
      <el-select v-model="form.position" disabled style="width: 100%">
        <el-option v-for="position in optionsPositions" :key="position.value" :label="position.label"
                   :value="position.value"/>
      </el-select>
    </el-form-item>
    <el-form-item label="职级" prop="level">
      <el-select v-model="form.level" disabled style="width: 100%">
        <el-option v-for="level in optionsLevel" :key="level.value" :label="level.label" :value="level.value"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)"
      >更新
      </el-button
      >
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElLoading} from "element-plus";
import {usePositionStore} from "@/stores/Person/Position";
import {useLevelStore} from "@/stores/Person/Level";
import {useDepartmentStore} from "@/stores/Person/Department";
import {useUserInfoStore} from "@/stores/User/UserInfo";
import {lookUpDictionaryApi} from "@/api/Dict";
import {userUpdateApi} from "@/api/User";
import router from "@/router";

const UserInfoStore = useUserInfoStore()
const PositionStore = usePositionStore()
const LevelStore = useLevelStore()
const DepartmentStore = useDepartmentStore()

const optionsPositions = PositionStore.positions
const optionsLevel = LevelStore.levels
const optionsDepartment = DepartmentStore.departments

const formSize = ref('default')
const formRef = ref<FormInstance>()
const form = reactive({
  name: '',
  phone: '',
  email: '',
  password: '',
  account: '',
  department: '',
  position: '',
  level: ''
})
const setForm = () => {
  lookUpDictionaryApi(UserInfoStore.departmentId).then(res => {
    form.department = res['data']
  })
  lookUpDictionaryApi(UserInfoStore.levelId).then(res => {
    form.level = res['data']
  })
  lookUpDictionaryApi(UserInfoStore.positionId).then(res => {
    form.position = res['data']
  })
  form.account = UserInfoStore.userAccount
  form.name = UserInfoStore.userName
  form.phone = UserInfoStore.userPhone
  form.email = UserInfoStore.userEmail
}
setForm()

//表单验证
const checkPhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('手机号不可为空'))
  } else if (value.length != 11 || value[0] != 1) {
    return callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 5, message: '请输入正确的姓名', trigger: 'blur'},
  ],
  password: {required: true, message: '请输入密码', trigger: 'blur'},
  phone: [{required: true, validator: checkPhone, trigger: 'blur'}],
  email: [{
    required: true,
    message: '请输入邮箱地址',
    trigger: 'blur',
  },
    {
      type: 'email',
      message: '请输入正确的邮箱',
      trigger: ['blur', 'change'],
    }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      userUpdateApi(form.account, form.email, UserInfoStore.userId, form.name, form.password, form.phone).then(res => {
        if (res != null) {
          const loading = ElLoading.service({
            lock: true,
            text: '正在更新信息',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          setTimeout(() => {
          }, 1000)
          if (res['code'] == 200) {
            // console.log("成功")
            loading.close()
            router.push('/login')
            localStorage.clear()
            sessionStorage.clear()
          } else {
            loading.close()
          }
        }
      })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}


</script>
